<template>
  <div class="activity-page">
    <!-- 搜索栏 -->
    <div class="search-container">
      <el-form inline :model="searchForm" class="search-form">
        <el-form-item label="活动标题">
          <el-input v-model="searchForm.title" placeholder="请输入活动标题"></el-input>
        </el-form-item>
        <el-form-item label="主办方">
          <el-input v-model="searchForm.organizer" placeholder="请输入主办方"></el-input>
        </el-form-item>
        <el-form-item label="活动状态">
          <el-select v-model="searchForm.status" placeholder="全部">
            <el-option label="全部" value=""></el-option>
            <el-option label="进行中" value="进行中"></el-option>
            <el-option label="已结束" value="已结束"></el-option>
            <el-option label="未开始" value="未开始"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker v-model="searchForm.createTime" type="daterange" range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期" placeholder="请选择时间范围"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作栏 -->
    <div class="action-bar">
      <el-button type="primary" class="create-btn">创建活动</el-button>
    </div>

    <!-- 表格布局 -->
    <div class="table-container">
      <el-table :data="activityList" border style="width: 100%">
        <el-table-column prop="index" label="序号" width="50" align="center"></el-table-column>
        <el-table-column prop="title" label="活动标题" min-width="140">
          <template #default="scope">
            <el-tooltip effect="dark" :content="scope.row.title" placement="top">
              <span class="content-text">{{ scope.row.title }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="organizer" label="主办方" min-width="100">
          <template #default="scope">
            <el-tooltip effect="dark" :content="scope.row.organizer" placement="top">
              <span>{{ scope.row.organizer }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="publishTime" label="发布时间" min-width="120">
          <template #default="scope">
            <el-tooltip effect="dark" :content="scope.row.publishTime || '-' " placement="top">
              <span class="content-text">{{ scope.row.publishTime || '-' }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="estimateTime" label="预估时间" min-width="140">
          <template #default="scope">
            <el-tooltip effect="dark" :content="scope.row.estimateTime || '-' " placement="top">
              <span class="content-text">{{ scope.row.estimateTime || '-' }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="结束时间" min-width="120">
          <template #default="scope">
            <el-tooltip effect="dark" :content="scope.row.endTime || '-' " placement="top">
              <span class="content-text">{{ scope.row.endTime || '-' }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center" sortable></el-table-column>
        <el-table-column prop="status" label="活动状态" min-width="90">
          <template #default="scope">
            <el-tooltip effect="dark" :content="scope.row.status" placement="top">
              <span :class="getStatusClass(scope.row.status)">{{ scope.row.status }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="列表图" min-width="80">
          <template #default="scope">
            <el-avatar :size="36" :src="scope.row.listImg" icon="el-icon-picture"></el-avatar>
          </template>
        </el-table-column>
        <el-table-column label="奖励类型" min-width="100">
          <template #default>
            <el-tooltip effect="dark" content="邀请人所得" placement="top">
              <span>邀请人所得</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="quota" label="名额数" min-width="80" />
        <el-table-column prop="amount" label="总金额" min-width="80" />
        <el-table-column label="活动链接" min-width="120">
          <template #default="scope">
            <el-tooltip effect="dark" :content="scope.row.link || '无链接'" placement="top">
              <div class="link-group">
                <el-button type="text" size="mini" @click="handleLink(scope.row.link)">查看链接</el-button>
                <el-button type="text" size="mini" icon="el-icon-document-copy"
                  @click="handleCopyLink(scope.row.link)"></el-button>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="推荐" min-width="80">
          <template #default="scope">
            <el-switch v-model="scope.row.recommend" :active-value="true" :inactive-value="false"
              disabled />
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="240" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-button type="primary" plain size="mini" @click="handleEdit(scope.$index)">编辑</el-button>
              <el-button type="danger" plain size="mini" @click="handleDelete(scope.$index)">删除</el-button>
              <el-button type="info" plain size="mini" @click="handleDetail(scope.$index)">详情</el-button>
              <el-button type="success" plain size="mini" @click="handleReport(scope.$index)">报名数据</el-button>
              <el-button type="warning" plain size="mini" @click="handleFormEdit(scope.$index)"
                style="margin-top: 6px;">表单编辑</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="activityList.length"
        :page-sizes="[10, 20, 50, 100]" :page-size="10" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>

    <!-- 编辑抽屉（修复富文本报错：改用el-input多行文本） -->
    <el-drawer
      title="活动编辑"
      :visible.sync="drawerVisible"
      direction="rtl"
      size="80%"
    >
      <el-form
        ref="activityForm"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="activity-form"
      >
        <!-- 第一行表单 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="活动标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入活动标题" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="主办方" prop="organizer">
              <el-select v-model="form.organizer" placeholder="请选择主办方">
                <el-option label="扬州大学" value="扬州大学" />
                <el-option label="南京邮电大学" value="南京邮电大学" />
                <el-option label="南京大学" value="南京大学" />
                <el-option label="南京航空航天大学" value="南京航空航天大学" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="活动状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态">
                <el-option label="未开始" value="未开始" />
                <el-option label="进行中" value="进行中" />
                <el-option label="已结束" value="已结束" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行表单 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="预估时间" prop="estimateTime">
              <el-input v-model="form.estimateTime" placeholder="格式：2025-11-07 至 2025-12-18" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker
                v-model="form.endTime"
                type="datetime"
                placeholder="选择结束时间"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发布时间" prop="publishTime">
              <el-date-picker
                v-model="form.publishTime"
                type="datetime"
                placeholder="选择发布时间"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行表单（图片上传） -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="列表图" prop="listImg">
              <el-upload
                class="upload-demo"
                action="/api/upload"
                :on-preview="handlePreview"
                :on-remove="(file, list) => handleRemove(file, list, 'listImg')"
                :on-success="(response, file) => handleUploadSuccess(response, file, 'listImg')"
                :file-list="form.listImgFileList"
                list-type="picture"
                limit="1"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <template #tip>
                  <div class="el-upload__tip">列表展示图片，尺寸：70x70(等比例)</div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="背景图" prop="bgImg">
              <el-upload
                class="upload-demo"
                action="/api/upload"
                :on-preview="handlePreview"
                :on-remove="(file, list) => handleRemove(file, list, 'bgImg')"
                :on-success="(response, file) => handleUploadSuccess(response, file, 'bgImg')"
                :file-list="form.bgImgFileList"
                list-type="picture"
                limit="1"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <template #tip>
                  <div class="el-upload__tip">网页端报名页背景图，尺寸：1920x1080</div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="详情图" prop="detailImg">
              <el-upload
                class="upload-demo"
                action="/api/upload"
                :on-preview="handlePreview"
                :on-remove="(file, list) => handleRemove(file, list, 'detailImg')"
                :on-success="(response, file) => handleUploadSuccess(response, file, 'detailImg')"
                :file-list="form.detailImgFileList"
                list-type="picture"
                limit="1"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <template #tip>
                  <div class="el-upload__tip">详情展示轮播图，尺寸：960x400</div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行表单 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="奖励类型" prop="rewardType">
              <el-select v-model="form.rewardType" placeholder="请选择">
                <el-option label="邀请人获得" value="邀请人获得" />
                <el-option label="报名人获得" value="报名人获得" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="名额数" prop="quota">
              <el-input v-model.number="form.quota" placeholder="请输入名额数" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总金额" prop="amount">
              <el-input v-model.number="form.amount" placeholder="请输入总金额" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第五行表单 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="分销规则模板" prop="distributionTemplate">
              <el-select v-model="form.distributionTemplate" placeholder="请选择">
                <el-option label="平均分类励规则" value="平均分类励规则" />
                <el-option label="设置名额奖励模板" value="设置名额奖励模板" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="推荐">
              <el-switch v-model="form.recommend" :active-value="true" :inactive-value="false" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="活动链接" prop="link">
              <el-input v-model="form.link" placeholder="请输入活动链接" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 活动描述（多行文本替代富文本） -->
        <el-form-item label="活动描述" prop="activityDesc">
          <el-input
            v-model="form.activityDesc"
            type="textarea"
            :rows="6"
            placeholder="请输入活动详细描述"
          />
        </el-form-item>

        <!-- 分销规则内容（多行文本替代富文本） -->
        <el-form-item label="分销规则内容" prop="distributionContent">
          <el-input
            v-model="form.distributionContent"
            type="textarea"
            :rows="6"
            placeholder="请输入分销规则详细内容"
          />
        </el-form-item>

        <!-- 抽屉底部按钮 -->
        <div class="drawer-footer">
          <el-button @click="drawerVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
export default {
  name: 'ActivityManagement',
  data() {
    return {
      searchForm: {
        title: '',
        organizer: '',
        status: '',
        createTime: []
      },
      activityList: [
        {
          index: 1,
          title: '扬州大学第12届国际青年学者论坛',
          organizer: '扬州大学',
          status: '进行中',
          publishTime: '2025-11-07 00:00:00',
          estimateTime: '2025-11-07 至 2025-12-18',
          endTime: '2025-12-18 00:00:00',
          createTime: '2025-11-07',
          listImg: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
          rewardType: '邀请人获得',
          quota: 0,
          amount: 0,
          distributionTemplate: '平均分类励规则',
          link: 'https://www.example.com',
          recommend: false,
          activityDesc: '扬州大学第12届国际青年学者论坛诚邀全球青年学者参与...',
          distributionContent: '本次活动采用平均分类励规则，邀请人可获得相应奖励...'
        },
        {
          index: 2,
          title: '南京邮电大学2025年全球人才交流会巴黎站',
          organizer: '南京邮电大学',
          status: '进行中',
          publishTime: '2025-11-07 00:00:00',
          estimateTime: '2025-11-07 至 2025-11-18',
          endTime: '2025-11-18 00:00:00',
          createTime: '2025-11-07',
          listImg: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
          rewardType: '邀请人获得',
          quota: 0,
          amount: 0,
          distributionTemplate: '平均分类励规则',
          link: 'https://www.example.com',
          recommend: false,
          activityDesc: '南京邮电大学2025年全球人才交流会巴黎站期待您的参与...',
          distributionContent: '本次活动采用平均分类励规则，详细规则如下...'
        }
      ],
      drawerVisible: false,
      form: {
        title: '',
        organizer: '',
        status: '',
        publishTime: '',
        estimateTime: '',
        endTime: '',
        listImg: '',
        listImgFileList: [],
        bgImg: '',
        bgImgFileList: [],
        detailImg: '',
        detailImgFileList: [],
        rewardType: '',
        quota: 0,
        amount: 0,
        distributionTemplate: '',
        recommend: false,
        link: '',
        activityDesc: '',
        distributionContent: ''
      },
      rules: {
        title: [{ required: true, message: '请输入活动标题', trigger: 'blur' }],
        organizer: [{ required: true, message: '请选择主办方', trigger: 'change' }],
        status: [{ required: true, message: '请选择活动状态', trigger: 'change' }],
        publishTime: [{ required: true, message: '请选择发布时间', trigger: 'change' }],
        rewardType: [{ required: true, message: '请选择奖励类型', trigger: 'change' }],
        distributionTemplate: [{ required: true, message: '请选择分销规则模板', trigger: 'change' }]
      }
    };
  },
  methods: {
    getStatusClass(status) {
      if (status === '进行中') return 'status-success';
      if (status === '已结束') return 'status-info';
      if (status === '未开始') return 'status-warning';
      return '';
    },
    handleSearch() {
      console.log('搜索条件：', this.searchForm);
    },
    handleReset() {
      this.searchForm = {
        title: '',
        organizer: '',
        status: '',
        createTime: []
      };
    },
    handleEdit(index) {
      const row = this.activityList[index];
      this.form = { ...row };
      // 处理图片上传的文件列表（模拟已上传的图片）
      if (row.listImg) {
        this.form.listImgFileList = [{ url: row.listImg, name: '列表图' }];
      }
      if (row.bgImg) {
        this.form.bgImgFileList = [{ url: row.bgImg, name: '背景图' }];
      }
      if (row.detailImg) {
        this.form.detailImgFileList = [{ url: row.detailImg, name: '详情图' }];
      }
      this.drawerVisible = true;
    },
    handleDelete(index) {
      this.$confirm('确定删除该活动吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.activityList.splice(index, 1);
      }).catch(() => {});
    },
    handleDetail(index) {
      console.log('活动详情：', this.activityList[index]);
    },
    handleReport(index) {
      console.log('报名数据：', this.activityList[index]);
    },
    handleFormEdit(index) {
      console.log('表单编辑：', this.activityList[index]);
    },
    handleLink(link) {
      if (link) {
        window.open(link, '_blank');
      }
    },
    handleCopyLink(link) {
      if (link) {
        navigator.clipboard.writeText(link).then(() => {
          this.$message.success('链接已复制到剪贴板');
        }).catch(() => {
          this.$message.error('复制失败，请手动复制');
        });
      } else {
        this.$message.warning('无链接可复制');
      }
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    },
    handlePreview(file) {
      console.log('预览图片', file);
    },
    handleRemove(file, fileList, type) {
      console.log('移除图片', file, fileList);
      this.form[type] = '';
    },
    handleUploadSuccess(response, file, type) {
      console.log('上传成功', response, file);
      this.form[type] = response.url; // 假设接口返回url字段
    },
    submitForm() {
      this.$refs.activityForm.validate((valid) => {
        if (valid) {
          // 此处可添加接口请求逻辑，提交form数据
          console.log('表单验证通过，提交数据：', this.form);
          // 模拟更新表格数据
          const index = this.activityList.findIndex(item => item.title === this.form.title);
          if (index > -1) {
            this.activityList.splice(index, 1, { ...this.form, index: index + 1 });
          }
          this.drawerVisible = false;
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    }
  }
};
</script>

<style scoped>
.activity-page {
  padding: 20px;
  display: flex;
  flex-direction: column;
  height: 100%;
  box-sizing: border-box;
}

.search-container {
  background-color: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

.action-bar {
  margin-bottom: 16px;
}

.table-container {
  flex: 1;
  overflow: hidden;
  width: 100%;
}

.content-text {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.status-success {
  color: #67c23a;
  font-weight: 500;
}

.status-info {
  color: #909399;
  font-weight: 500;
}

.status-warning {
  color: #e6a23c;
  font-weight: 500;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.link-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.activity-form {
  padding: 20px;
}

.drawer-footer {
  text-align: right;
  margin-top: 20px;
}

.upload-demo {
  width: 100%;
}

@media (max-width: 1200px) {
  .search-form {
    flex-direction: column;
    align-items: flex-start;
  }
}

:deep(.el-table) {
  width: 100% !important;
}

:deep(.el-table th),
:deep(.el-table td) {
  border-right: 1px solid #ebeef5;
}

:deep(.el-table th:last-child),
:deep(.el-table td:last-child) {
  border-right: none;
}

:deep(.el-table .cell) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>